﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Diagnostics;
using System.Diagnostics.Contracts;

namespace Mvvm {
	public class RelayCommand : ICommand {
		private readonly Action<object> execute;
		private readonly Predicate<object> canExecute;

		public RelayCommand(Action<object> execute)
			: this(execute, null) {
		}

		public RelayCommand(Action<object> execute, Predicate<object> canExecute) {
			Contract.Requires(execute != null);
			this.execute = execute;
			this.canExecute = canExecute;
		}

		public bool CanExecute(object parameter) {
			return canExecute == null ? true : canExecute(parameter);
		}

		public event EventHandler CanExecuteChanged {
			add { CommandManager.RequerySuggested += value; }
			remove { CommandManager.RequerySuggested -= value; }
		}

		public void Execute(object parameter) {
			execute(parameter);
		}

		public bool SafeExecute(object parameter) {
			if (CanExecute(parameter)) {
				Execute(parameter);
				return true;
			}
			return false;
		}
	}
}
